package com.xiezc.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiezc.common.entity.BookInfo;
import com.xiezc.common.result.BaseResult;
import com.xiezc.common.result.ListResult;
import com.xiezc.common.result.PageResult;
import com.xiezc.common.result.PojoResult;
import com.xiezc.data.service.BookInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiezc
 * @since 2018-10-06
 */
@RestController
@RequestMapping("/bookInfo")
public class BookInfoController {

    @Resource
    BookInfoService bookInfoService;

    @PostMapping("add")
    public BaseResult addBookInfo(@RequestBody BookInfo bookInfo) {

        boolean save = bookInfoService.save(bookInfo);
        return save ? BaseResult.success() : BaseResult.fail("500", "save error");
    }

    @GetMapping("getAllUrls")
    public ListResult<String> getAllBookUrl() {

        LambdaQueryWrapper<BookInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(BookInfo::getFetchUrl);
        List<BookInfo> list = bookInfoService.list(wrapper);
        Set<String> collect = list.parallelStream()
                .map(bookInfo -> bookInfo.getFetchUrl())
                .collect(Collectors.toSet());
        return ListResult.success(collect);
    }

    @GetMapping("getPageBookInfo")
    public PageResult<BookInfo> getPageBookInfo(@RequestParam("current") Integer current,
                                                @RequestParam("size") Integer size) {

        LambdaQueryWrapper<BookInfo> wrapper = new LambdaQueryWrapper<>();
        Page<BookInfo> bookInfoPage = new Page<>(current, size);
        IPage<BookInfo> page = bookInfoService.page(bookInfoPage, wrapper);
        return PageResult.success(page.getRecords(), page.getCurrent(), page.getSize(), page.getTotal());
    }

    @GetMapping("getById")
    public PojoResult<BookInfo> getById(Integer id) {

        LambdaQueryWrapper<BookInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookInfo::getId, id);
        BookInfo one = bookInfoService.getOne(wrapper);
        return PojoResult.success(one);
    }


    @GetMapping("getByUrl")
    public PojoResult<BookInfo> getByUrl(String url) {
        LambdaQueryWrapper<BookInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookInfo::getFetchUrl, url);
        BookInfo one = bookInfoService.getOne(wrapper);
        return PojoResult.success(one);
    }
}

